package com.sziit.se.highconcurrency.common.tool;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.sziit.se.highconcurrency.common.constant.SystemConstants;
import com.sziit.se.highconcurrency.common.exception.NullDataException;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    private JwtUtils() {
    }

    public static final int MINUTE = 60 * 1000;
    /**
     * 过期时间
     */
    public static final int EXPIRE_TIME = 60 * MINUTE * 24;

    public static final String CLAIM_KEY = "account";

    /**
     * 生成签名
     *
     * @param account  用户名
     * @param password 用户的密码
     * @return 加密的token
     */
    public static String sign(String account, String password) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(password);
        // 附带account信息
        return JWT.create().withClaim(CLAIM_KEY, account).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String account, String secret) {
        try {
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim(CLAIM_KEY, account).build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getAccount(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(CLAIM_KEY).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 根据request中的token获取用户账号
     */
    public static String getAccount(HttpServletRequest request) {
        String accessToken = request.getHeader(SystemConstants.TOKEN_HEADER);
        String account = getAccount(accessToken);
        if (StrUtil.isEmpty(account)) {
            throw new NullDataException("userId:" + account);
        }
        return account;
    }

}
